package com.ruix.app.widget.chatrow;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.Toast;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMVoiceMessageBody;
import com.hyphenate.util.EMLog;
import com.ruix.app.RuiApplication;
import com.ruix.app.cache.CacheBaseFactory;
import com.ruix.app.cache.CacheFactory;
import com.ruix.app.manager.UserManager;
import com.ruix.app.model.User;
import com.ruix.app.service.UpdateAppService;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 语音row播放点击事件监听
 *
 */
public class ChatRowVoicePlayClickListener implements View.OnClickListener {
    private static final String TAG = "VoicePlayClickListener";
    EMMessage message;
    EMVoiceMessageBody voiceBody;
    ImageView voiceIconView;

    private AnimationDrawable voiceAnimation = null;
    MediaPlayer mediaPlayer = null;
    ImageView iv_read_status;
    Activity activity;
    private EMMessage.ChatType chatType;
    private BaseAdapter adapter;
    private AsyncTask downtask;

    public static boolean isPlaying = false;
    public static ChatRowVoicePlayClickListener currentPlayListener = null;
    public static String playMsgId;

    public ChatRowVoicePlayClickListener(EMMessage message, ImageView v, ImageView iv_read_status, BaseAdapter adapter, Activity context) {
        this.message = message;
        voiceBody = (EMVoiceMessageBody) message.getBody();
        this.iv_read_status = iv_read_status;
        this.adapter = adapter;
        voiceIconView = v;
        this.activity = context;
        this.chatType = message.getChatType();
    }

    public void stopPlayVoice() {
        if (isPlaying) {
            voiceAnimation.stop();
            if (message.direct() == EMMessage.Direct.RECEIVE) {
                voiceIconView.setImageResource(com.hyphenate.easeui.R.drawable.ease_chatfrom_voice_playing);
            } else {
                voiceIconView.setImageResource(com.hyphenate.easeui.R.drawable.ease_chatto_voice_playing);
            }
            // stop play voice
            if (mediaPlayer != null) {
                mediaPlayer.stop();
                mediaPlayer.release();
            }
            isPlaying = false;
            playMsgId = null;
            adapter.notifyDataSetChanged();
        }
    }

    public void playVoice(String filePath) {
//		if (!(new File(filePath).exists())) {
//			return;
//		}
        playMsgId = message.getMsgId();
        AudioManager audioManager = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);

        mediaPlayer = new MediaPlayer();
//		if (EaseUI.getInstance().getSettingsProvider().isSpeakerOpened()) {
//			audioManager.setMode(AudioManager.MODE_NORMAL);
//			audioManager.setSpeakerphoneOn(true);
//			mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
//		} else {
//			audioManager.setSpeakerphoneOn(false);// 关闭扬声器
//			// 把声音设定成Earpiece（听筒）出来，设定为正在通话中
//			audioManager.setMode(AudioManager.MODE_IN_CALL);
//			mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
//		}
        try {
//			mediaPlayer.setDataSource(activity, Uri.parse(filePath));
//			FileInputStream inputStream = activity.getResources().getAssets().open("1.amr");
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.reset();
            mediaPlayer.setDataSource(filePath);
//			mediaPlayer.setDataSource(inputStream);
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    // TODO Auto-generated method stub
                    mediaPlayer.release();
                    mediaPlayer = null;
                    stopPlayVoice(); // stop animation
                }

            });
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
                }
            });
            isPlaying = true;
            currentPlayListener = this;
//			mediaPlayer.start();
            showAnimation();

            // 如果是接收的消息
            if (message.direct() == EMMessage.Direct.RECEIVE) {
                if (!message.isAcked() && chatType == EMMessage.ChatType.Chat) {
                    // 告知对方已读这条消息
                    EMClient.getInstance().chatManager().ackMessageRead(message.getFrom(), message.getMsgId());
                }
                if (!message.isListened() && iv_read_status != null && iv_read_status.getVisibility() == View.VISIBLE) {
                    // 隐藏自己未播放这条语音消息的标志
                    iv_read_status.setVisibility(View.INVISIBLE);
                    message.setListened(true);
                    EMClient.getInstance().chatManager().setVoiceMessageListened(message);
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println();
        }
    }

    // show the voice playing animation
    private void showAnimation() {
        // play voice, and start animation
        if (message.direct() == EMMessage.Direct.RECEIVE) {
            voiceIconView.setImageResource(com.hyphenate.easeui.R.anim.voice_from_icon);
        } else {
            voiceIconView.setImageResource(com.hyphenate.easeui.R.anim.voice_to_icon);
        }
        voiceAnimation = (AnimationDrawable) voiceIconView.getDrawable();
        voiceAnimation.start();
    }

    @Override
    public void onClick(View v) {
//        String st = activity.getResources().getString(com.hyphenate.easeui.R.string.Is_download_voice_click_later);
        if (isPlaying) {
            if (playMsgId != null && playMsgId.equals(message.getMsgId())) {
                currentPlayListener.stopPlayVoice();
                return;
            }
            currentPlayListener.stopPlayVoice();
        }
        if (message.status() == EMMessage.Status.SUCCESS) {
            downloadResorce();//INPROGRESS
        } else if (message.status() == EMMessage.Status.INPROGRESS
                || message.status() == EMMessage.Status.FAIL){
            if (!TextUtils.isEmpty(voiceBody.getLocalUrl())){
                playVoice(voiceBody.getLocalUrl()); //
            }
        }


//        if (message.direct() == EMMessage.Direct.SEND) {
//            // for sent msg, we will try to play the voice file directly
//            playVoice(voiceBody.getRemoteUrl());
//        } else {
//            if (message.status() == EMMessage.Status.SUCCESS) {
//                if (voiceBody.getRemoteUrl() != null) {
//                    playVoice(voiceBody.getRemoteUrl());
//                } else {
//                    File file = new File(voiceBody.getLocalUrl());
//                    if (file.exists() && file.isFile()) {
//                        playVoice(voiceBody.getLocalUrl());
//                        EMLog.e(TAG, "file not exist");
//                    } else {
//                        playVoice(voiceBody.getRemoteUrl());
//                    }
//                }
//            } else if (message.status() == EMMessage.Status.INPROGRESS) {
//                Toast.makeText(activity, st, Toast.LENGTH_SHORT).show();
//            } else if (message.status() == EMMessage.Status.FAIL) {
//                Toast.makeText(activity, st, Toast.LENGTH_SHORT).show();
//                new AsyncTask<Void, Void, Void>() {
//
//                    @Override
//                    protected Void doInBackground(Void... params) {
//                        EMClient.getInstance().chatManager().downloadAttachment(message);
//                        return null;
//                    }
//
//                    @Override
//                    protected void onPostExecute(Void result) {
//                        super.onPostExecute(result);
//                        adapter.notifyDataSetChanged();
//                    }
//
//                }.execute();
//
//            }
//
//        }
    }

    //下载 缓存  并播放

    public void downloadResorce(){
        if (downtask != null){
            downtask.cancel(true);
            downtask = null;
        }
        downtask =  new AsyncTask<String, Integer, String>() {

            @Override
            protected String doInBackground(String... params) {
                //缓存中获取 没有缓存文件
                //网络中获取
                String lessonId = UserManager.sharedInstance().getCurrentLessonID();
                String mid = message.getMsgId();

               String path =  CacheFactory.loadVoicePach(lessonId,mid);
                if (path != null && new File(path).exists()){
                    return path;
                } else {
                    //下载 文件file
                    String fpath =  savePath(lessonId ,mid);
                    String ppath =  download(fpath,voiceBody.getRemoteUrl());
                    if (ppath != null) {
                        CacheFactory.cacheVoicePach(lessonId, mid, path);
                        return ppath;
                    }
                }

                return null;
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                super.onProgressUpdate(values);
            }

            @Override
            protected void onPostExecute(String result) {
                if (result != null) {
                    playVoice(result);
                }
            }
        }.execute("");
    }

    private String savePath(String lessonId,String mid){
        String path =   RuiApplication.getAppContext().getFilesDir().getAbsolutePath();
        String filePath =  path +"/"+ lessonId+"/"+mid;
        return  filePath;
    }

    private String download(String filePath, String downloadUrl){
        final File file = new File(filePath);
        File dir = file.getParentFile();
        if (!dir.exists()) {
            dir.mkdirs();
        }

        HttpURLConnection httpConnection = null;
        InputStream is = null;
        FileOutputStream fos = null;
        int updateTotalSize = 0;
        java.net.URL url;
        try {
            url = new URL(downloadUrl);
            httpConnection = (HttpURLConnection) url.openConnection();
            httpConnection.setConnectTimeout(20000);
            httpConnection.setReadTimeout(20000);

            if (httpConnection.getResponseCode() != 200) {
                return null;
            }

            updateTotalSize = httpConnection.getContentLength();

            if (file.exists()) {
                if (updateTotalSize == file.length()) {
                    // 下载完成
                    return file.getAbsolutePath();
                } else {
                    file.delete();
                }
            }
            file.createNewFile();
            is = httpConnection.getInputStream();
            fos = new FileOutputStream(file, false);
            byte buffer[] = new byte[4096];

            int readSize = 0;
            while ((readSize = is.read(buffer)) > 0) {
                fos.write(buffer, 0, readSize);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (httpConnection != null) {
                httpConnection.disconnect();
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return file.getAbsolutePath();
    }



}
